import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/model/product/product_ad_model.dart';
import 'package:labcloud_app/model/product/product_model.dart';
import 'package:provider/provider.dart';
import '../../data/product_ad.dart';
import '../../data/product.dart';
import '../../widget/async_image.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  void initState() {
    super.initState();
    // 延迟加载数据，确保context可用
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadAds();
      _loadProducts();
    });
  }

  Future<void> _loadAds() async {
    final productAdModel = Provider.of<ProductAdModel>(context, listen: false);
    await productAdModel.loadAds(context);
  }

  Future<void> _loadProducts() async {
    final productModel = Provider.of<ProductModel>(context, listen: false);
    await productModel.loadProducts(context, limit: 10);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('首页')),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              SizedBox(height: 150, width: double.infinity, child: _banner()),
              SizedBox(height: 4),
              _productList(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _banner() {
    return Consumer<ProductAdModel>(
      builder: (context, productAdModel, child) {
        if (productAdModel.isLoading) {
          return const Center(child: CircularProgressIndicator());
        }

        if (productAdModel.errorMessage?.isNotEmpty == true) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(productAdModel.errorMessage!),
                ElevatedButton(
                  onPressed: _loadAds,
                  child: const Text('重试'),
                ),
              ],
            ),
          );
        }

        final ads = productAdModel.productAdList ?? [];
        if (ads.isEmpty) {
          return const Center(child: Text('暂无广告数据'));
        }

        return CarouselSlider(
          options: CarouselOptions(
            autoPlay: true,
            aspectRatio: 2.0,
            enlargeCenterPage: true,
          ),
          items: ads.map((ad) {
            return GestureDetector(
              onTap: () {
                // 检查是否有productId，如果有则跳转到商品详情页
                if (ad.productId != null) {
                  Navigator.pushNamed(
                    context,
                    '/product_detail',
                    arguments: {
                      'productId': ad.productId,
                    },
                  );
                } else {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('无法跳转到商品详情页')),
                  );
                }
              },
              child: Container(
                decoration: BoxDecoration(color: Colors.grey),
                child: AsyncImageWidget(
                  imageUrl: ad.coverAddr ?? '',
                  fit: BoxFit.cover,
                ),
              ),
            );
          }).toList(),
        );
      },
    );
  }

  Widget _productList() {
    return Consumer<ProductModel>(
      builder: (context, productModel, child) {
        if (productModel.isLoading) {
          return const Center(child: CircularProgressIndicator());
        }

        if (productModel.errorMessage?.isNotEmpty == true) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(productModel.errorMessage!),
                ElevatedButton(
                  onPressed: _loadProducts,
                  child: const Text('重试'),
                ),
              ],
            ),
          );
        }

        final products = productModel.productList ?? [];
        if (products.isEmpty) {
          return const Center(child: Text('暂无产品数据'));
        }

        return GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 0.75,
            crossAxisSpacing: 10,
            mainAxisSpacing: 10,
          ),
          itemCount: products.length,
          itemBuilder: (context, index) {
            return _productItem(products[index]);
          },
        );
      },
    );
  }

  Widget _productItem(Product product) {
    return GestureDetector(
      onTap: () {
        Navigator.pushNamed(
          context,
          "/product_detail",
          arguments: {"productId": product.id},
        );
      },
      child: Card(
        elevation: 4.0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12.0),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: ClipRRect(
                borderRadius: const BorderRadius.vertical(top: Radius.circular(12.0)),
                child: AsyncImageWidget(
                  imageUrl: product.coverAddr ?? '',
                  fit: BoxFit.cover,
                  width: double.infinity,
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    product.title ?? '未知产品',
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: const TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 14,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '¥${product.price ?? 0}',
                        style: const TextStyle(
                          color: Colors.red,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Row(
                        children: [
                          const Icon(Icons.star, color: Colors.orange, size: 14),
                          Text(
                            '${product.rate ?? 0}',
                            style: const TextStyle(fontSize: 12),
                          ),
                        ],
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}